package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: TimeLineService
 * @Author:王晨晗
 * @Description: 时间线表业务类
 * @Date: 2021/12/31/10:42
 */
@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    //将动态id异步写入好友的时间线表
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId){
        try {
            //根据用户id 获取其好友id
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> usersList = mongoTemplate.find(query, Users.class);

            //判断好友集合是否为空
            if (CollUtil.isEmpty(usersList)) {
                //返回成功(无好友可写)
                return CompletableFuture.completedFuture("ok");
            }
            //遍历好友集合
            for (Users users : usersList) {
                //创建时间线表对象
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());     //时间线表id
                timeLine.setDate(System.currentTimeMillis());       //发布时间
                timeLine.setPublishId(publishId);           //动态id
                timeLine.setUserId(userId);         //发布者id
                //写入数据
                mongoTemplate.save(timeLine, "quanzi_time_line_" + users.getFriendId());
            }
        } catch (Exception e) {
            log.error("写入好友时间线表失败~ userId = " + userId + ", publishId = " + publishId, e);
            return CompletableFuture.completedFuture("error");
        }
        //响应成功写入
        return CompletableFuture.completedFuture("ok");
    }
}
